﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Zhy.DigitaPlatform.DeviceAccess.Base;
using Zhy.DigitaPlatform.DeviceAccess.Transfer;
using Zhy.DigitaPlatform.Entities;

namespace Zhy.DigitaPlatform.DeviceAccess.Execute
{
    /// <summary>
    /// 第三方库
    /// </summary>
    internal class ModbusRTU3th : ExecuteObject
    {
        Modbus.Device.IModbusSerialMaster master;
        /// <summary>
        /// 查找共用的通信对象
        /// </summary> 
        /// <param name="props">设备的组件通讯属性集合</param>
        /// <param name="tos">通讯对象集合</param>
        internal override Result Match(List<DevicePropItemEntity> props, List<TransferObject> tos)
        {
            var ps = props.Where(p => p.PropName == "PortName").Select(p => p.PropValue).ToList();
            var result = this.Match(props, tos, ps, "SerialUnit");
            master = Modbus.Device.ModbusSerialMaster.CreateRtu(this.TransferObject.TUnit as SerialPort);
            return result;
        }

        /// <summary>
        /// 读取组件通讯数据
        /// </summary>
        /// <param name="mas">一次性读取多个属性值</param>
        /// <returns></returns>
        public override Result Read(List<CommAddress> variables)
        {
            // 获取重试次数
            var prop = this.Props.FirstOrDefault(p => p.PropName == "TryCount");
            int tryCount = 30;
            if (prop != null)
                int.TryParse(prop.PropValue, out tryCount); // 绑定重试次数
            Result connectState = this.TransferObject.Connect(tryCount); // 连接
            if (!connectState.Status)
                throw new Exception(connectState.Message);


            //master.ReadHoldingRegisters()
            return base.Read(variables); // 读取数据
        }
    }
}
